package com.nuanshui.heatedloan.extension.validator;

import org.springframework.validation.Errors;
import org.springframework.validation.FieldError;
import org.springframework.validation.Validator;

import com.nuanshui.framework.exception.BizException;
import com.nuanshui.framework.exception.GlobalErrorCode;


public class ParamValidator implements Validator {

	@Override
	public boolean supports(final Class<?> clazz) {
		return true;
	}

	@Override
	public void validate(final Object target, final Errors errors) {
		if (errors.hasFieldErrors()) {
			StringBuilder sb = new StringBuilder();
			for (FieldError fieldError : errors.getFieldErrors()) {
				sb.append(fieldError.getField());
				sb.append(getErrorMessage(fieldError));
				sb.append(",");
			}
			String errorMessage = sb.toString();
			if (errorMessage.endsWith(",")) {
				errorMessage = errorMessage.substring(0,
						errorMessage.length() - 1);
			}
			throw new BizException(GlobalErrorCode.INVALID_ARGUMENT, errorMessage);
		}
	}

	/**
	 * 获取错误信息
	 * 
	 * @return
	 */
	private String getErrorMessage(final FieldError fieldError) {
		String code = fieldError.getCode();
		if ("typeMismatch".equals(code)) {
			return "类型不正确";
		}
		return fieldError.getDefaultMessage();

	}
}
